package com.taiyuan.zfmvp.controller;

import cn.hutool.Hutool;
import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taiyuan.zfmvp.utils.Base64Util;
import com.taiyuan.zfmvp.utils.HttpUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.PrivateKey;
import java.security.Signature;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * @param
 * @Author: zhoufang@sxjtjt.net
 * @Descriiption:
 * @Date 2023/9/7
 * @return
 */
public class testMain {
    public static void main(String[] args) throws Exception {
        String zipFilePath = "C:\\Users\\86186\\Desktop\\物贸物流\\压缩包\\上传图片.zip";
        readZip(zipFilePath);
        //aaa();c1b59b23204f937e75398d8cc1704cja887



        /*tokenVo to = new tokenVo();
        to.setClientId("4111ea97dffa163e9d2a183dea15fweb");
        to.setClientSecret("f11ffb5c041b11ea97dffa163e9d2a29");
        to.setUserName("18211111111");
        to.setUpass(Base64Util.encryptBASE64("abcd1234".getBytes()));
        to.setSignData("RGXxfLvatMfoyFzqHOAw3Pn4rrJS9+pzczfnlAFGlF7GEx8ZqK2PZp716Td7ZC0Zi06eAnfS5DtyUc1bESapy062Gcoed3pD0o0oeo9er+T+98io2dBkjOpKekIuNXYsibMhnmvw3WTdhvbOlbY1lCVbVLayyy0atLcl8tXsoWo=");
        to.setTime(currentTime());
        to.setBranchCode("49adb23841da3214518shanxijiantou");

        String url = "http://220.194.138.143:60080/ntocc-tms-api/openApi/getToken";
        //String url = "https://www.sxcigzhwl.com/ntocc-tms-api/openApi/getToken";
        System.out.println("token请求地址："+ url);
        System.out.println("token请求参数："+ JSON.toJSONString(to));
        String result = null;
        try {
            result = HttpUtil.post(url, JSON.toJSONString(to));
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("token请求回参："+ result);
        JSONObject resultJson = JSONObject.parseObject(result);
        String token = resultJson.getString("data");
        System.out.println(token);*/

        //二次加密token
        //String newToken = getToken(token);
        /*System.out.println(newToken);
        String geturl = "http://220.194.138.143:60080/ntocc-tms-api/openApi/driverList";
        //String geturl = "http://220.194.138.143:60080/ntocc-tms-api/openApi/driverList";

        String getParam = "driverType=1&pageNum=1&pageSize=20&total=50&branchCodeExt=49adb23841da3214518shanxijiantou&phone=13696858842&vehicleLicenseNumber=陕AX5062";
        //String getResult = HttpUtils.sendGet(geturl,getParam,newToken);
        String getResult = HttpUtils.sendGet2(geturl+"?"+getParam,newToken);
        System.out.println(getResult);
        JSONObject driverJson = JSONObject.parseObject(getResult);
        JSONObject data = driverJson.getJSONObject("data");
        int total = (Integer)data.get("total");
        System.out.println("查询到数据条数"+total);
        JSONArray array = data.getJSONArray("records");
        String partyCode =  array.getJSONObject(0).getString("partyCode");
        System.out.println("partyCode:"+partyCode);*/


       /* DriverAPIDTO driverAPIDTO = new DriverAPIDTO();
        driverAPIDTO.setName("tet");
        driverAPIDTO.setPhone("123132");
        driverAPIDTO.setLicenseNumber("12312");
        driverAPIDTO.setLoadWeight("123");
        driverAPIDTO.setSignature(signData(token));
*/

        /*OrderAPIDTO orderAPIDTO = new OrderAPIDTO();
        orderAPIDTO.setShipperSubdivisionCode("0");//装货地点国家行政区划代码
        orderAPIDTO.setShipperAddress("山西省太原市清徐县");//装货地址
        orderAPIDTO.setShipperDetailAddress("东于镇西高白村307国道南12号");//装货详细地址
        orderAPIDTO.setShipperName("申亮田");//发货人
        orderAPIDTO.setShipperPhone("18222222222");//发货人电话
        orderAPIDTO.setConsigneeSubdivisionCode("0");//卸货地国家行政区划代码
        orderAPIDTO.setConsigneeAddress("山西省长治市潞州区");//卸货地地址
        orderAPIDTO.setConsigneeDetailAddress("东大街9号");//卸货地详细地址
        orderAPIDTO.setConsigneeName("赵清龙");//收货人
        orderAPIDTO.setConsigneePhone("18735194923");//收货人手机号
        orderAPIDTO.setCoalBigType("1");//货物名称编码（大类）
        orderAPIDTO.setCoalType("1");//货物名称编码（小类）
        orderAPIDTO.setCoalPrice("1");// 货物单价
        orderAPIDTO.setCoalUnit("元");//货物单位
        orderAPIDTO.setPrice("1");//运费单价
        orderAPIDTO.setIsTrunk("0");//运费单位
        orderAPIDTO.setLimitWastageAmount("0");// 合理损耗数量
        orderAPIDTO.setLimitWastageType("0");//合理损耗单位
        orderAPIDTO.setLastLoadingTime("2023-07-24 20:20:00");//最晚装车时间
        orderAPIDTO.setLastUnloadingTime("2023-07-27 20:20:00");//最晚卸车时间
        orderAPIDTO.setTransportType(1);// 运输方式
        orderAPIDTO.setSignature(signData(token));
        orderAPIDTO.setTime(currentTimefahuo());
        orderAPIDTO.setBranchCode("49adb23841da3214518shanxijiantou");

        //新增参数
        orderAPIDTO.setWeight("1");
        orderAPIDTO.setDriverCode("5ee7b2f8372341aab820cbc625e9f64f");

        //String url = "http://220.194.138.143:60080/ntocc-tms-api/openApi/getToken";
        //String urlfabu = "https://www.sxcigzhwl.com/ntocc-tms-api/openApi/submitOrderDetail";
        String urlfabu = "http://220.194.138.143:60080/ntocc-tms-api/openApi/submitOrderDetail";*/
        /*String urlfabu = "http://220.194.138.143:60080/ntocc-tms-api/openApi/saveDriver";
        System.out.println("请求地址："+ urlfabu);
        System.out.println("请求参数："+ JSON.toJSONString(driverAPIDTO));
        String resultfabu = null;
        try {
            resultfabu = HttpUtils.httpPost(urlfabu, JSON.toJSONString(driverAPIDTO),newToken);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("发布货源返回参数："+ resultfabu);*/




    }

    public static String signData(String token){
        try {
            //分配的密钥
            String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ/cYyKIl7s8ZWlr89T9iuY0kvIQZSLZpEju+606PYxHHZCGPUFxZqabbRIDaCAZ4tmG4nVcVgnIvVPsp6dkkdPymjuZ70vCA5HyK3TSDlsVLhqsNeDWsGWF/g9Du85iQz/OI83DyhKmcsa4al7hwSp+vOVVydjKeizygsOYqscXAgMBAAECgYAEcZ4fEQiVJhB0bF5pCep5JcL9kAkcfX8jBXzhJUcd7CgqCVR2/XQ3pqBsj/dICFz7yqBNWBWOmUVYdn6rZfdLwsMLPP1q/BP5Byy2N7wMSZWK7iZaBv27JPgj1OtMZFw2Y6oZILdpIKczO9HP99IcryS7vzAkpfFc2hlbDVB/4QJBAMydmFD2Kj4SlYqmZDz+urC785myqswM+uJx5b+MwBN/edrMyZfNHczSJy93j12bTqgrIXcIL86oNguJsBCY01ECQQDIAZWJk5gvd2vCld9Ay7lYIdCq2mvXPenoeZXSNeXNLR1Jhda5ucDgcFQEPA0zMmgR1qKwtZktVog4P7Vt4knnAkAW/prwdkmXAjWmCD75j9LhK64blrWVCtxi+FPOa/3l8wx5p0v8cEOqEe/vaKtG5L45Leer3dKpkcPJFicgJlyRAkAMZLS8cq3iexbtVtYfsMAKawYAIErAarC83BPhk79qqFoBPU7h8VW3Up6SKJp0yrHSMSehpY8ZVRxZx/DZH0WPAkEAzAEtDEudh8y/rNuuqtX/fooqQjVNfqZj8dkkCRCzvBzld5s+YLXKRezWPOSBgP2SQuFM8XYvBHusFZAbCnKZaw==";



            PrivateKey privateKey1 = SecureUtil.generatePrivateKey("MD5withRSA", Base64.decode(privateKey));
            //进行签名服务 token加密
            byte[] data = token.getBytes();
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(privateKey1);
            signature.update(data);
            byte[] signedData = signature.sign();
            //base64编码加密后的数据
            String str = Base64.encode(signedData);
            //System.out.println("加密签名数据:" + str);
            return  str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String currentTime() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sf.format(new Date());
    }

    public static String currentTimefahuo() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sf.format(new Date());
    }



    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            //下面注释的setRequestProperty可要可不要
//            conn.setRequestProperty("accept", "application/json, text/javascript, */*; q=0.01");
//            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
//            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String readZip(String fileName) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
        ZipInputStream zis = new ZipInputStream(bis);
        ZipEntry entry ;//用于获取压缩文件中的文件或文件夹
        StringBuffer sb = new StringBuffer();
        File file = new File(fileName);
        File temp = file;
        String parentZipParent = file.getParent();//获取上级文件夹解压到这里
        ZipFile zip = new ZipFile(fileName);




        List<MultipartFile> myFiles = new ArrayList<>();
        while((entry = zis.getNextEntry())!=null){
            if(!entry.isDirectory()){
                System.out.println("file:"+entry.getName());
                //File file = new File(entry.getName());
                //myFiles.add(getMultipartFile(file));
                temp = new File(parentZipParent + "\\" + entry.getName());
                if (!temp.getParentFile().exists()) {
                    temp.getParentFile().mkdirs();
                }

                OutputStream os = new FileOutputStream(temp);
                //通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流
                InputStream is = zip.getInputStream(entry);
                int len = 0;
                while ((len = is.read()) !=-1) {
                    os.write(len);
                }
                myFiles.add(getMultipartFile(temp));
            }else{
                //System.out.println("file:"+entry.getName());

            }
        }

        for (int i = 0; i < myFiles.size(); i++) {
            System.out.println(myFiles.get(i).getOriginalFilename());
        }


        return sb.toString();
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }


    public static void aaa(){
        try {
            //分配的密钥
            String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ/cYyKIl7s8ZWlr89T9iuY0kvIQZSLZpEju+606PYxHHZCGPUFxZqabbRIDaCAZ4tmG4nVcVgnIvVPsp6dkkdPymjuZ70vCA5HyK3TSDlsVLhqsNeDWsGWF/g9Du85iQz/OI83DyhKmcsa4al7hwSp+vOVVydjKeizygsOYqscXAgMBAAECgYAEcZ4fEQiVJhB0bF5pCep5JcL9kAkcfX8jBXzhJUcd7CgqCVR2/XQ3pqBsj/dICFz7yqBNWBWOmUVYdn6rZfdLwsMLPP1q/BP5Byy2N7wMSZWK7iZaBv27JPgj1OtMZFw2Y6oZILdpIKczO9HP99IcryS7vzAkpfFc2hlbDVB/4QJBAMydmFD2Kj4SlYqmZDz+urC785myqswM+uJx5b+MwBN/edrMyZfNHczSJy93j12bTqgrIXcIL86oNguJsBCY01ECQQDIAZWJk5gvd2vCld9Ay7lYIdCq2mvXPenoeZXSNeXNLR1Jhda5ucDgcFQEPA0zMmgR1qKwtZktVog4P7Vt4knnAkAW/prwdkmXAjWmCD75j9LhK64blrWVCtxi+FPOa/3l8wx5p0v8cEOqEe/vaKtG5L45Leer3dKpkcPJFicgJlyRAkAMZLS8cq3iexbtVtYfsMAKawYAIErAarC83BPhk79qqFoBPU7h8VW3Up6SKJp0yrHSMSehpY8ZVRxZx/DZH0WPAkEAzAEtDEudh8y/rNuuqtX/fooqQjVNfqZj8dkkCRCzvBzld5s+YLXKRezWPOSBgP2SQuFM8XYvBHusFZAbCnKZaw==";



            PrivateKey privateKey1 = SecureUtil.generatePrivateKey("MD5withRSA", Base64.decode(privateKey));
            //进行签名服务 token加密
            byte[] data = "f11ffb5c041b11ea97dffa163e9d2a29".getBytes();
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(privateKey1);
            signature.update(data);
            byte[] signedData = signature.sign();
            //base64编码加密后的数据
            String str = Base64.encode(signedData);
            System.out.println("加密签名数据:" + str);
            System.out.println("加密的密码："+Base64Util.encryptBASE64("abcd1234".getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getToken(String token) {
        long floor = new Date().getTime() / 1000;
        token += Long.toHexString(floor);
        token = adjust(token);
        token = Base64.encode(token);
        token = adjust(token);
        return token;
    }

    /**
     * 接口鉴权加密方式
     * 加密字符串默认长度大于2，方法内部不做校验
     * @param str
     * @return
     */
    private static String adjust(String str){
        char[] cs = str.toCharArray();
        int len = cs.length;
        double l = Math.floor((double)len/2);
        int start = (cs[0]+cs[--len])%3;
        for(int i=start;i<l;i++){
            if(cs[i]!=cs[len-i]){
                char tmp = cs[i];
                cs[i] = cs[len-i];
                cs[len-i] = tmp;
                i+=(cs[i]+cs[len-i])%2;
            }
        }
        return String.valueOf(cs);
    }

    public static void sign(){
        try {
            //分配的密钥
            String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ/cYyKIl7s8ZWlr89T9iuY0kvIQZSLZpEju+606PYxHHZCGPUFxZqabbRIDaCAZ4tmG4nVcVgnIvVPsp6dkkdPymjuZ70vCA5HyK3TSDlsVLhqsNeDWsGWF/g9Du85iQz/OI83DyhKmcsa4al7hwSp+vOVVydjKeizygsOYqscXAgMBAAECgYAEcZ4fEQiVJhB0bF5pCep5JcL9kAkcfX8jBXzhJUcd7CgqCVR2/XQ3pqBsj/dICFz7yqBNWBWOmUVYdn6rZfdLwsMLPP1q/BP5Byy2N7wMSZWK7iZaBv27JPgj1OtMZFw2Y6oZILdpIKczO9HP99IcryS7vzAkpfFc2hlbDVB/4QJBAMydmFD2Kj4SlYqmZDz+urC785myqswM+uJx5b+MwBN/edrMyZfNHczSJy93j12bTqgrIXcIL86oNguJsBCY01ECQQDIAZWJk5gvd2vCld9Ay7lYIdCq2mvXPenoeZXSNeXNLR1Jhda5ucDgcFQEPA0zMmgR1qKwtZktVog4P7Vt4knnAkAW/prwdkmXAjWmCD75j9LhK64blrWVCtxi+FPOa/3l8wx5p0v8cEOqEe/vaKtG5L45Leer3dKpkcPJFicgJlyRAkAMZLS8cq3iexbtVtYfsMAKawYAIErAarC83BPhk79qqFoBPU7h8VW3Up6SKJp0yrHSMSehpY8ZVRxZx/DZH0WPAkEAzAEtDEudh8y/rNuuqtX/fooqQjVNfqZj8dkkCRCzvBzld5s+YLXKRezWPOSBgP2SQuFM8XYvBHusFZAbCnKZaw==";



            PrivateKey privateKey1 = SecureUtil.generatePrivateKey("MD5withRSA", Base64.decode(privateKey));
            //进行签名服务 token加密
            byte[] data = "367eb7d0e6f8cfba942r03320d10ff32336".getBytes();
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(privateKey1);
            signature.update(data);
            byte[] signedData = signature.sign();
            //base64编码加密后的数据
            String str = Base64.encode(signedData);
            System.out.println("加密签名数据:" + str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
